package com.yjc.blog.controller;


import com.yjc.blog.domain.bo.UserBo;
import com.yjc.blog.domain.bo.UserLoginBO;
import com.yjc.blog.domain.bo.UserSave;
import com.yjc.blog.domain.vo.PageVO;
import com.yjc.blog.domain.vo.UserLoginVO;
import com.yjc.blog.domain.vo.UserVO;
import com.yjc.blog.service.IUserService;
import com.yjc.blog.utils.R;
import com.yjc.blog.utils.SnowFlake;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author yjc
 * @since 2024-11-01
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private SnowFlake snowFlake;

    @Resource
    private RedisTemplate redisTemplate;;

    @GetMapping("/list")
    public R<PageVO<UserVO>> userList(@Valid UserBo bo){
        PageVO<UserVO> list = userService.userList(bo);
        R<PageVO<UserVO>> r = new R<>();
        r.setContent(list);
        return r;
    }
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable("id") Long id){
        userService.userDelete(id);
        return new R<>();
    }
    @PostMapping("/save")
    public R save(@RequestBody UserSave save){
        save.setPassword(DigestUtils.md5DigestAsHex(save.getPassword().getBytes()));
        userService.userSave(save);
        return new R<>();
    }

    @PostMapping("/login")
    public R<UserLoginVO> login(@RequestBody @Valid UserLoginBO bo){
        bo.setPassword(DigestUtils.md5DigestAsHex(bo.getPassword().getBytes()));
        R<UserLoginVO> r = new R<>();
        UserLoginVO vo = userService.login(bo);
        long token = snowFlake.nextId();
        redisTemplate.opsForValue().set(token,bo,3600 * 24, TimeUnit.SECONDS);
        vo.setToken(token);
        r.setContent(vo);
        return r;
    }

    @GetMapping("/logout/{token}")
    public R logOut(@PathVariable long token){
        redisTemplate.delete(token);
        return new R<>();
    }
}
